﻿using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace Codemonk.Updater.Server
{
    internal class SocketClient : IClient
    {
        private Socket client;
        public Socket Client
        {
            get { return client; }
            set
            {
                try
                {
                    client = value;
                    var data = new byte[4];
                    client.Receive(data, 0, 4, 0);
                    string[] realdata = null;
                    using (MemoryStream stream = new MemoryStream())
                    {
                        var length = BitConverter.ToInt32(data, 0);
                        int index = 0;
                        data = new byte[2048];
                        while (index < length)
                        {
                            int count = client.Receive(data, 0, 2048, 0);
                            if (count <= 0) break;
                            index += count;
                            stream.Write(data, 0, count);
                        }
                        realdata = Encoding.UTF8.GetString(stream.ToArray()).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    AppID = realdata[1].Substring(realdata[1].IndexOf("=") + 1);
                    FileName = realdata[0].Substring(realdata[0].IndexOf("=") + 1);
                }
                catch { }
            }
        }

        public string AppID { get; set; }

        public string FileName { get; set; }

        public System.IO.Stream Stream
        {
            get { return null; }
            set
            {
                if (value == null) { client.Close(); return; }
                using (MemoryStream stream = StreamHelper.Transfer(value))
                {
                    byte[] length = BitConverter.GetBytes((int)(stream.Length));
                    client.Send(length);
                    client.Send(stream.ToArray());
                    client.Close();
                }
            }
        }
    }
}
